@page "/builder/list"
@using FOPS.Abstract.K8S.Entity
@using FOPS.Abstract.K8S.Server
@using FOPS.Abstract.MetaInfo.Entity
@using FOPS.Abstract.MetaInfo.Server
@using FS.Extends
@using FOPS.Abstract.Builder.Server
@using System.Timers
@inject IIocManager _iocManager;
@inject NavigationManager nav;
@inject IJSRuntime js;

<div class="layui-row layui-col-space10">
    <div class="layui-col-xs6 layui-col-md8">
        <div class="layui-card">
            <div class="layui-card-header">
                构建
                <select style="display:inline;width: 200px;" @onchange="GroupChange">
                    <option value="0">全部</option>
                    @foreach (var projectGroupVO in _lstGroup)
                    {
                        <option value="@projectGroupVO.Id">@projectGroupVO.Name</option>
                    }
                </select>

                <select style="display:inline;width: 200px;" @onchange="ClusterChange">
                    @foreach (var clusterVO in _lstCluster)
                    {
                        <option value="@clusterVO.Id">@clusterVO.Name - @clusterVO.RuntimeEnvType</option>
                    }
                </select>
                <div class="layui-right">
                    <button class="layui-btn layui-btn-danger" @onclick="AddAllBuild"><i class="am-icon-plus"></i> 全部构建</button>
                </div>
            </div>
            <div class="layui-card-body">
                <div class="layui-form layui-border-box layui-table-view" lay-filter="LAY-table-1" style="">
                    <div class="layui-table-box">
                        <div class="layui-table-header">
                            <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                                <thead>
                                <tr>
                                    <th data-field="ID">
                                        <div class="layui-table-cell laytable-cell-14-0-0">
                                            <span>ID</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-1">
                                            <span>项目名称</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-2">
                                            <span>构建方式</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-2">
                                            <span>git拉取</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-3">
                                            <span>镜像版本</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-3">
                                            <span>集群版本</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-4">
                                            <span>上次成功</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-5">
                                            <span>上次失败</span>
                                        </div>
                                    </th>
                                    <th data-field="Type">
                                        <div class="layui-table-cell laytable-cell-14-0-6">
                                            <span>操作</span>
                                        </div>
                                    </th>
                                </tr>
                                </thead>
                            </table>
                        </div>
                        <div class="layui-table-body layui-table-main">
                            <table cellspacing="0" cellpadding="0" border="0" class="layui-table" lay-skin="auto" lay-size="sm">
                                <tbody>
                                @foreach (var info in _lst)
                                {
                                    <tr>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-0"> @info.Id</div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-1">
                                                <a href="/project/update/@info.Id">@info.Name</a>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-2">
                                                @info.BuildType.GetName()
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-2">
                                                <span>@((DateTime.Now - info.GitPullAt).GetDateDesc())</span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-3">
                                                @info.DockerVer
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-3">
                                                @info.DicClusterVer[_clusterId].DockerVer
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-4">
                                                @if (info.DicClusterVer[_clusterId].DeploySuccessAt.Year >= 2021)
                                                {
                                                    <a href="/builder/log/@info.DicClusterVer[_clusterId].BuildSuccessId">@((DateTime.Now - info.DicClusterVer[_clusterId].DeploySuccessAt).GetDateDesc())</a>
                                                }
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-5">
                                                @if (info.DicClusterVer[_clusterId].DeployFailAt.Year >= 2021)
                                                {
                                                    <a href="/builder/log/@info.DicClusterVer[_clusterId].BuildFailId">@((DateTime.Now - info.DicClusterVer[_clusterId].DeployFailAt).GetDateDesc())</a>
                                                }
                                            </div>
                                        </td>
                                        <td>
                                            <div class="layui-table-cell laytable-cell-14-0-6">
                                                <button class="layui-btn layui-btn-sm layui-btn-danger" @onclick="() => AddBuild(info)">构建</button>
                                                <button class="layui-btn layui-btn-sm" @onclick="() => SetImages(info)">同步</button>
                                            </div>
                                        </td>
                                    </tr>
                                }
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <PageSplit PageIndex="1" PageSize="@_pageSize" TotalCount="@_totalCount" PageUrl="/builder/list/{index}"></PageSplit>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-xs6 layui-col-md4">
        <div class="layui-card">
            <div class="layui-card-header" id="anchor-play-header">
                构建队列
            </div>
            <div class="layui-card-body">
                <div class="layui-form layui-border-box layui-table-view" lay-filter="LAY-table-1">
                    <div class="layui-table-box">
                        <BuildList></BuildList>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<style>
    .laytable-cell-14-0-0{ width: 60px; }
    .laytable-cell-14-0-1{ width: 170px; }
    .laytable-cell-14-0-2{ width: 110px; }
    .laytable-cell-14-0-3{ width: 80px; }
    .laytable-cell-14-0-4{ width: 110px; }
    .laytable-cell-14-0-5{ width: 110px; }
    .laytable-cell-14-0-6{ width: 140px; }
</style>

@code{

    private int _totalCount;
    private int _pageSize = 999;

    private List<ProjectVO> _lst = new();
    private List<YamlTplVO> _lstTpl = new();
    private List<ClusterVO> _lstCluster = new();
    private List<GitVO> _lstGit = new();
    private List<ProjectGroupVO> _lstGroup = new();

    private int _clusterId;
    private int _groupId;

    bool _isFirst;

    protected override async Task OnInitializedAsync()
    {
        if (_isFirst) return;
        _isFirst = true;

        _lstGroup = await _iocManager.Resolve<IProjectGroupService>().ToListAsync() ?? new();
    // Git
        _lstGit = await _iocManager.Resolve<IGitService>().ToListAsync() ?? new();

    // 模板
        _lstTpl = await _iocManager.Resolve<IYamlTplService>().ToListAsync() ?? new();
        _lstTpl = _lstTpl.OrderByDescending(o => o.Id).ToList();

    // 集群
        _lstCluster = await _iocManager.Resolve<IClusterService>().ToListAsync() ?? new();
        if (_lstCluster.Count > 0) _clusterId = _lstCluster[0].Id;

        await GetList();
    }

    private Task ClusterChange(ChangeEventArgs args)
    {
        _clusterId = args.Value.ConvertType(0);
        _lst = new();
        return GetList();
    }

    private Task GroupChange(ChangeEventArgs args)
    {
        _groupId = args.Value.ConvertType(0);
        _lst = new();
        return GetList();
    }

    private async Task GetList()
    {
    // 重新读取所有项目列表
        _lst = _groupId > 0 ? await _iocManager.Resolve<IProjectService>().ToListAsync(_groupId) :
            await _iocManager.Resolve<IProjectService>().ToListAsync();
        _lst ??= new();

    // 遍历项目组ID
        var projectGroupIds = _lst.Select(o => o.GroupId).Distinct().ToList();
        foreach (var projectGroupId in projectGroupIds)
        {
            var id = projectGroupId;
            var projectGroup = _lstGroup.Find(o => o.Id == id);
            if (projectGroup == null) continue;

    // 如果项目组不包含当前选中的集群，则移除项目
            if (!projectGroup.ClusterIds.Contains(_clusterId))
                _lst.RemoveAll(o => o.GroupId == projectGroupId);
        }

        _lst = _lst.OrderByDescending(o => o.Id).ToList();
        _totalCount = _lst.Count;

        foreach (var project in _lst)
        {
            var git = _lstGit.Find(o => o.Id == project.GitId);
            if (git == null) continue;
            project.GitId     = git.Id;
            project.GitPullAt = git.PullAt;

            if (!project.DicClusterVer.ContainsKey(_clusterId))
                project.DicClusterVer[_clusterId] = new ClusterVer {DockerVer = "0"};
        }
    }

    private async Task AddBuild(ProjectVO project)
    {
        var load = await js.InvokeAsync<int>("layer.load", 0, "{shade: false}");
        try
        {
            await _iocManager.Resolve<IBuildService>().Add(project.Id, _clusterId);
            await GetList();
            await js.InvokeVoidAsync("layer.msg", "已加入到队列", new {icon = 1, title = "执行结果"});
        }
        catch (Exception e)
        {
            await js.InvokeVoidAsync("layer.alert", e.Message, new {icon = 2, title = "加入失败"});
        }
        await js.InvokeVoidAsync("layer.close", load);
    }

    private async Task AddAllBuild()
    {
        if (_lst.Count == 0)
        {
            await js.InvokeVoidAsync("layer.msg", "当前没有需要构建的项目");
            return;
        }
        var load = await js.InvokeAsync<int>("layer.load", 0, "{shade: false}");
        try
        {
            foreach (var project in _lst)
            {
                await _iocManager.Resolve<IBuildService>().Add(project.Id, _clusterId);
            }
            await js.InvokeVoidAsync("layer.msg", "已加入到队列", new {icon = 1, title = "执行结果"});
        }
        catch (Exception e)
        {
            await js.InvokeVoidAsync("layer.alert", e.Message, new {icon = 2, title = "加入失败"});
        }
        await js.InvokeVoidAsync("layer.close", load);
    }

    /// 更新集群镜像版本
    private async Task SetImages(ProjectVO project)
    {
        var load = await js.InvokeAsync<int>("layer.load", 0, "{shade: false}");
        try
        {
            var runShellResult = await _iocManager.Resolve<IKubectlOpr>().SetImages(_clusterId, project.DockerVer.ConvertType(0), project, null);
            if (runShellResult.IsError) await js.InvokeVoidAsync("layer.alert", runShellResult.OutputBr, new {icon = 2, title = "出错了"});
            else
            {
                await _iocManager.Resolve<IBuildService>().Success(_clusterId, project, 0);
                await GetList();
                await js.InvokeVoidAsync("layer.msg", runShellResult.OutputBr, new {icon = 1, title = "执行结果"});
            }
        }
        catch (Exception e)
        {
            await js.InvokeVoidAsync("layer.alert", e.Message, new {icon = 2, title = "加入失败"});
        }
        await js.InvokeVoidAsync("layer.close", load);
    }

}